package com.wyzz.hr.action;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.base.BaseDownloadAction;
import com.wyzz.hr.bo.IAttendmonthlyBO;
import com.wyzz.hr.bo.IEmpAddConfBo;
import com.wyzz.hr.bo.IEmpTypeBO;
import com.wyzz.hr.bo.ILocationBO;
import com.wyzz.hr.bo.impl.ExaminDateUtil;
import com.wyzz.hr.pojo.Attendmonthly;
import com.wyzz.hr.pojo.Attendperiod;
import com.wyzz.hr.pojo.Empaddconf;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Emptype;
import com.wyzz.hr.pojo.Location;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.StringUtil;

public class SearchAttendmonthly extends BaseDownloadAction {

	public SearchAttendmonthly() {
		msgNotCloseStatus = "{0}\u8003\u52E4\u6570\u636E\u4E0D\u662F\u5C01\u5E10\u72B6\u6001\uFF0C\u4E0D\u80FD\u89E3\u5C01\uFF01";
		msgOpenSuccess = "{0}\u8003\u52E4\u6570\u636E\u89E3\u5C01\u6210\u529F\uFF01";
		msgCanNotClose = "{0}\u8003\u52E4\u6570\u636E\u4E3A\u521D\u59CB\u5316\u72B6\u6001\uFF0C\u4E0D\u80FD\u8FDB\u884C\u5C01\u5E10\uFF01";
		msgCloseSuccess = "{0}\u8003\u52E4\u6570\u636E\u5C01\u5E10\u6210\u529F\uFF01";
		msgCanNotCloseApp = "{0}\u8003\u52E4\u6570\u636E\u4E0D\u662F\u521D\u59CB\u5316\u72B6\u6001\uFF0C\u4E0D\u80FD\u8FDB\u884C\u5C01\u5E10\u7533\u8BF7\u64CD\u4F5C\uFF01";
		msgCloseAppSucc = "{0}\u8003\u52E4\u6570\u636E\u5C01\u5E10\u7533\u8BF7\u6210\u529F\uFF01";
		msgCanNotDel = "\u672C\u6708\u8003\u52E4\u6570\u636E\u5DF2\u5C01\u5E10\uFF0C\u4E0D\u5141\u8BB8\u5220\u9664\uFF01";
		msgDelSucc = "\u5220\u9664\u6210\u529F\u3002";
		msgDelFail = "\u5220\u9664\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\uFF01";
		msgYearmonthEmpty = "\u8981\u521D\u59CB\u5316\u7684\u5E74\u6708\u4E0D\u80FD\u4E3A\u7A7A\uFF01\u8BF7\u9009\u62E9\u5E74\u6708\u540E\u91CD\u8BD5\uFF01";
		msgInitSucc = "{0}\u521D\u59CB\u5316\u8003\u52E4\u6570\u636E\u6210\u529F\u3002";
		msgInitFail = "{0}\u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\uFF01";
		page = new Pager();
		yearMonth = DateUtil.formatTodayToS("yyyy-MM");
		searchOrExport = null;
		docStream = null;
		contentDisposition = null;
		serverFileName = null;
		searchMode = DatabaseSysConfigManager.getInstance().getProperty(
				"sys.examin.hourtoday.mode");
		suffixStr = "\u5929";
		suffixFld = "Days";
	}

	public String execute() throws Exception {
		getDrillDownList();
		execParameter();
		if ("export".equals(searchOrExport)) {
			attendmonthlyList = searchAttendmonthly(null, yearMonth);
			if ("export".equals(searchOrExport)) {
				getClass();
				return downloadToExcel(attendmonthlyList, "OExamMonthly",
						outmatchModelId, "attmEmpId");
			}
		}
		attendmonthlyList = searchAttendmonthly(page, yearMonth);
		return "success";
	}

	private List searchAttendmonthly(Pager pager, String yearMonth) {
		yearMonth = yearMonth.replaceAll("-", "");
		DetachedCriteria dc = DetachedCriteria.forClass(Attendmonthly.class);
		if ("SUB".equals(super.authorityCondition))
			addSubDC(dc, "emp", 4);
		addCriteria(dc, yearMonth);
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		return attendmothlyBO.searchAttendmonthly(pager, dc);
	}

	private void addCriteria(DetachedCriteria dc, String yearMonth) {
		dc.createAlias(Attendmonthly.PROP_ATTM_EMP_ID, "emp", 1);
		dc.createAlias((new StringBuilder()).append("emp.").append(
				Employee.PROP_EMP_DEPT_NO).toString(), "empOrgDept", 1);
		dc.createAlias((new StringBuilder()).append("emp.").append(
				Employee.PROP_EMP_PB_NO).toString(), "empOrgPb", 1);
		dc.createAlias((new StringBuilder()).append("emp.").append(
				Employee.PROP_EMP_LOCATION_NO).toString(), "empOrgLoc", 1);
		dc.add(Restrictions.eq(Attendmonthly.PROP_ATTM_YEARMONTH, yearMonth));
		BaseCrit.addEmpDC(dc, "emp", emp);
		if (employee != null) {
			BaseCrit.addDC(dc, (new StringBuilder()).append("emp.").append(
					Employee.PROP_ID).toString(), "eq", new String[] { employee
					.getId() });
			BaseCrit.addDeptDC(dc, (new StringBuilder()).append("emp.").append(
					Employee.PROP_EMP_DEPT_NO).toString(),
					(new StringBuilder()).append("emp.").append(
							Employee.PROP_EMP_PB_NO).toString(), null, employee
							.getEmpDeptNo());
			BaseCrit.addDC(dc, (new StringBuilder()).append("emp.").append(
					Employee.PROP_EMP_TYPE).toString(), Emptype.PROP_ID,
					new Object[] { employee.getEmpType() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("emp.").append(
					Employee.PROP_EMP_LOCATION_NO).toString(),
					Location.PROP_ID, new Object[] { employee
							.getEmpLocationNo() });
		}
		if (searchType != 0)
			switch (searchType) {
			case 1: // '\001'
				dc.add(Restrictions.gt("attmLeaveHours", new BigDecimal(0)));
				break;

			case 2: // '\002'
				dc.add(Restrictions.gt("attmLateTimes", new BigDecimal(0)));
				break;

			case 3: // '\003'
				dc.add(Restrictions.gt("attmEarlyLeave", new BigDecimal(0)));
				break;

			case 4: // '\004'
				dc.add(Restrictions.gt("attmOvertimeHours", new BigDecimal(0)));
				break;

			case 5: // '\005'
				dc.add(Restrictions.gt("attmOffDutyHours", new BigDecimal(0)));
				break;
			}
		if ("export".equals(searchOrExport)) {
			dc.setFetchMode(Attendmonthly.PROP_ATTM_DEPT, FetchMode.JOIN);
			dc.setFetchMode(Attendmonthly.PROP_ATTM_LOCATION, FetchMode.JOIN);
			dc.setFetchMode(Attendmonthly.PROP_ATTM_EMPTYPE, FetchMode.JOIN);
			dc.setFetchMode(Attendmonthly.PROP_ATTM_PB_NO, FetchMode.JOIN);
			addOrders(dc, null, new String[] { (new StringBuilder()).append(
					"emp.").append(Employee.PROP_EMP_DISTINCT_NO).append("-up")
					.toString() });
		} else {
			addOrders(dc, page, new String[] { (new StringBuilder()).append(
					"emp.").append(Employee.PROP_EMP_DISTINCT_NO).append("-up")
					.toString() });
			page.splitPage(dc);
		}
	}

	private void execParameter() {
		String config = (String) DatabaseSysConfigManager.getInstance()
				.getProperties().get("sys.examin.month.sum");
		Date dateArr[] = ExaminDateUtil.getDateArray(yearMonth, config);
		startDate = formatDate(dateArr[0]);
		endDate = formatDate(dateArr[1]);
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		period = attendmothlyBO.loadAttendperiod(yearMonth);
		if (period == null)
			setStatus(Integer.valueOf(0));
		else
			setStatus(period.getAttpStatus());
	}

	private void getDrillDownList() {
		ILocationBO localbo = (ILocationBO) SpringBeanFactory
				.getBean("locationBO");
		locations = localbo.FindEnabledLocation();
		IEmpTypeBO emptypebo = (IEmpTypeBO) SpringBeanFactory
				.getBean("emptypeBO");
		empType = emptypebo.FindEnabledEmpType();
		IEmpAddConfBo empAddConfBo = (IEmpAddConfBo) BaseAction
				.getBean("empAddConfBo");
		attdConfList = empAddConfBo.listByTable("attend");
		Iterator i$ = attdConfList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Empaddconf conf = (Empaddconf) i$.next();
			if (conf != null)
				conf
						.setFieldValueList(getListByString(conf
								.getEadcFieldValue()));
		} while (true);
	}

	public String reOpenAttendperiod() {
		if (StringUtils.isEmpty(yearMonth))
			return "success";
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		Attendperiod period = attendmothlyBO.loadAttendperiod(yearMonth);
		if (period == null)
			addErrorInfo(StringUtil.message(msgNotCloseStatus,
					new Object[] { yearMonth }));
		else if (period.getAttpStatus().intValue() == 2) {
			period.setAttpStatus(Integer.valueOf(0));
			attendmothlyBO.updateObject(period);
			addSuccessInfo(StringUtil.message(msgOpenSuccess,
					new Object[] { yearMonth }));
		} else {
			addErrorInfo(StringUtil.message(msgNotCloseStatus,
					new Object[] { yearMonth }));
		}
		return "success";
	}

	public String closeAttendperiod() {
		if (StringUtils.isEmpty(yearMonth))
			return "success";
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		Attendperiod period = attendmothlyBO.loadAttendperiod(yearMonth);
		if (period == null)
			addErrorInfo(StringUtil.message(msgCanNotClose,
					new Object[] { yearMonth }));
		else if (period.getAttpStatus().intValue() == 1) {
			period.setAttpStatus(Integer.valueOf(2));
			attendmothlyBO.updateObject(period);
			addSuccessInfo(StringUtil.message(msgCloseSuccess,
					new Object[] { yearMonth }));
		} else {
			addErrorInfo(StringUtil.message(msgCanNotClose,
					new Object[] { yearMonth }));
		}
		return "success";
	}

	public String applyAttendperiod() {
		if (StringUtils.isEmpty(yearMonth))
			return "success";
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		Attendperiod period = attendmothlyBO.loadAttendperiod(yearMonth);
		if (period == null)
			addErrorInfo(StringUtil.message(msgCanNotCloseApp,
					new Object[] { yearMonth }));
		else if (period.getAttpStatus().intValue() == 0) {
			if (super.authorityCondition.equalsIgnoreCase("HRM"))
				period.setAttpStatus(Integer.valueOf(2));
			else if (super.authorityCondition.equalsIgnoreCase("HR"))
				period.setAttpStatus(Integer.valueOf(1));
			attendmothlyBO.updateObject(period);
			addSuccessInfo(StringUtil.message(msgCloseAppSucc,
					new Object[] { yearMonth }));
		} else {
			addErrorInfo(StringUtil.message(msgCanNotCloseApp,
					new Object[] { yearMonth }));
		}
		return "success";
	}

	private String formatDate(Date date) {
		return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
	}

	public String deleteAttendmonthly() {
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		Attendperiod period = attendmothlyBO.loadAttendperiod(yearMonth);
		if (period != null && period.getAttpStatus().intValue() == 2) {
			addErrorInfo(StringUtil.message(msgCanNotDel, new Object[0]));
			return "error";
		}
		if (attendmothlyBO.deleteAttendmonthly(delAttendIds)) {
			addSuccessInfo(StringUtil.message(msgDelSucc, new Object[0]));
			return "success";
		} else {
			addErrorInfo(StringUtil.message(msgDelFail, new Object[0]));
			return "error";
		}
	}

	public String calDailyToAttendmonthly() {
		if (StringUtils.isEmpty(yearMonth)) {
			addSuccessInfo(msgYearmonthEmpty);
			return "success";
		}
		IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) getBean("attendmonthlyBo");
		if (attendmothlyBO.exeMonthlySummary(yearMonth)) {
			addSuccessInfo(StringUtil.message(msgInitSucc,
					new Object[] { yearMonth }));
			return "success";
		} else {
			addErrorInfo(StringUtil.message(msgInitFail,
					new Object[] { yearMonth }));
			return "error";
		}
	}

	public String getEmpType(String id) {
		if (id == null || id == "")
			return "";
		for (Iterator iterator = empType.iterator(); iterator.hasNext();) {
			Emptype type = (Emptype) iterator.next();
			if (id.equals(type.getId()))
				return type.getEmptypeName();
		}

		return "";
	}

	public List getListByString(String str) {
		if (str == null || "".equals(str))
			return null;
		List result = new ArrayList();
		String temp[] = str.split(",");
		for (int i = 0; i < temp.length; i++)
			result.add(temp[i]);

		return result;
	}

	public String formatBD(BigDecimal input) {
		if (input == null) {
			return null;
		} else {
			DecimalFormat df = new DecimalFormat("#0.0 ");
			return df.format(input);
		}
	}

	public Pager getPage() {
		return page;
	}

	public void setPage(Pager page) {
		this.page = page;
	}

	public String getEmp() {
		return emp;
	}

	public void setEmp(String emp) {
		this.emp = emp;
	}

	public List getLocations() {
		return locations;
	}

	public void setLocations(List locations) {
		this.locations = locations;
	}

	public List getEmpType() {
		return empType;
	}

	public void setEmpType(List empType) {
		this.empType = empType;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	public Integer getAuth() {
		return auth;
	}

	public void setAuth(Integer auth) {
		this.auth = auth;
	}

	public int getSearchType() {
		return searchType;
	}

	public void setSearchType(int searchType) {
		this.searchType = searchType;
	}

	public List getAttendmonthlyList() {
		return attendmonthlyList;
	}

	public void setAttendmonthlyList(List attendmonthlyList) {
		this.attendmonthlyList = attendmonthlyList;
	}

	public String getYearMonth() {
		return yearMonth;
	}

	public void setYearMonth(String yearMonth) {
		this.yearMonth = yearMonth;
	}

	public List getAttdConfList() {
		return attdConfList;
	}

	public void setAttdConfList(List attdConfList) {
		this.attdConfList = attdConfList;
	}

	public String getSuffixStr() {
		return suffixStr;
	}

	public void setSuffixStr(String suffixStr) {
		this.suffixStr = suffixStr;
	}

	public String getSuffixFld() {
		return suffixFld;
	}

	public void setSuffixFld(String suffixFld) {
		this.suffixFld = suffixFld;
	}

	public String getSearchOrExport() {
		return searchOrExport;
	}

	public void setSearchOrExport(String searchOrExport) {
		this.searchOrExport = searchOrExport;
	}

	public FileInputStream getDocStream() {
		return docStream;
	}

	public void setDocStream(FileInputStream docStream) {
		this.docStream = docStream;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getServerFileName() {
		return serverFileName;
	}

	public void setServerFileName(String serverFileName) {
		this.serverFileName = serverFileName;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public Attendperiod getPeriod() {
		return period;
	}

	public void setPeriod(Attendperiod period) {
		this.period = period;
	}

	public String getOutmatchModelId() {
		return outmatchModelId;
	}

	public void setOutmatchModelId(String outmatchModelId) {
		this.outmatchModelId = outmatchModelId;
	}

	public String getSearchMode() {
		return searchMode;
	}

	public void setSearchMode(String searchMode) {
		this.searchMode = searchMode;
	}

	public String getDelAttendIds() {
		return delAttendIds;
	}

	public void setDelAttendIds(String delAttendIds) {
		this.delAttendIds = delAttendIds;
	}

	private String msgNotCloseStatus;
	private String msgOpenSuccess;
	private String msgCanNotClose;
	private String msgCloseSuccess;
	private String msgCanNotCloseApp;
	private String msgCloseAppSucc;
	private String msgCanNotDel;
	private String msgDelSucc;
	private String msgDelFail;
	private String msgYearmonthEmpty;
	private String msgInitSucc;
	private String msgInitFail;
	private static final long serialVersionUID = 0xfffffffebd50f49fL;
	private Pager page;
	private List attendmonthlyList;
	private String emp;
	private List locations;
	private List empType;
	private Employee employee;
	private Integer status;
	private Attendperiod period;
	private Integer auth;
	private String yearMonth;
	private String delAttendIds;
	private int searchType;
	private List attdConfList;
	private String startDate;
	private String endDate;
	private String searchOrExport;
	private String outmatchModelId;
	public final String outputIoName = "OExamMonthly";
	private FileInputStream docStream;
	private String contentDisposition;
	private String serverFileName;
	private String searchMode;
	private String suffixStr;
	private String suffixFld;
}
